﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using System.Threading;

public partial class UserManage_UserAdd : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    private static string clientName = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1007"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }
            
            dataBind();
            dataBindClient();
        }
    }

    private void dataBind()
    {
        DataTable dtRoles = userManage.GetAllRoles();
        chkRolesList.DataSource = dtRoles;
        chkRolesList.DataTextField = "RoleName";
        chkRolesList.DataValueField = "RoleID";
        chkRolesList.DataBind();
    }

    #region 调出框用到的所有方法
    private void dataBindClient()
    {
        ViewState["OrderBy"] = "Status";
        ViewState["Accending"] = "desc";
        FillClientType();

        string sqlStr = "SELECT S.* FROM Sy_Client as S where Status=1 ";
        SqlParameter[] parms = null;
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = clientManage.GetClientList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvClientList.DataSource = view;
        gvClientList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }

    }

    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        List<SqlParameter> list = new List<SqlParameter>();
        sqlstr = "";
        if (ViewState["Value"] != null)
        {
            if (ViewState["Name"].ToString().ToLower() == "cnshortname")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@HKShortName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@ENGShortName", ViewState["Value"].ToString()));
                sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGShortName like '%' +  @ENGShortName + '%' or HKShortName like '%' +  @HKShortName + '%')";
            }
            else if (ViewState["Name"].ToString().ToLower() == "cnname")
            {
                list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@HKName", ViewState["Value"].ToString()));
                list.Add(new SqlParameter("@ENGName", ViewState["Value"].ToString()));
                sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGName like '%' +  @ENGName + '%' or HKName like '%' +  @HKName + '%')";

            }
            //else if (ViewState["Name"].ToString().ToLower() == "title")
            //{
            //    list.Add(new SqlParameter("@ColumnName", ViewState["Value"].ToString()));
            //    list.Add(new SqlParameter("@HKTitle", ViewState["Value"].ToString()));
            //    list.Add(new SqlParameter("@ENGTitle", ViewState["Value"].ToString()));
            //    sqlstr += " and ( " + ViewState["Name"].ToString() + " like '%' +  @ColumnName + '%' or ENGTitle like '%' +  @ENGTitle + '%' or HKTitle like '%' +  @HKTitle + '%')";

            //}
        }

        if (ViewState["Type"] != null)
        {
            list.Add(new SqlParameter("@CType", ViewState["Type"]));
            sqlstr += " and PKID in(select ClientID from Sy_ClientType where SyCodeID=@CType)";
        }       

        parms = list.ToArray();
    }

    private void FillClientType()
    {
        DataTable dt = clientManage.GetClientTypeList();
        ddlType.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlType.DataTextField = "ENGName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlType.DataTextField = "HKName";
        }
        else
        {
            ddlType.DataTextField = "Name";
        }
        ddlType.DataValueField = "PKID";
        ddlType.DataBind();
        ddlType.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }


    protected void gvClientList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvClientList.PageIndex = e.NewPageIndex;
        dataBindClient();
    }

    protected void gvClientList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {           
            Label lblCNName = (Label)e.Row.FindControl("lblCNName");
            Label lblENName = (Label)e.Row.FindControl("lblENName");
            Label lblHKName = (Label)e.Row.FindControl("lblHKName");         

            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
            {
                lblENName.Visible = true;               
                lblCNName.Visible = false;
                lblHKName.Visible = false;
              
            }
            else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                lblENName.Visible = false;             
                lblCNName.Visible = false;
                lblHKName.Visible = true;               
            }
            else
            {
                lblENName.Visible = false;              
                lblCNName.Visible = true;
                lblHKName.Visible = false;              
            }


        }
    }

    protected void gvClientList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindClient();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {

        if (txtName.Text != string.Empty)
        {
            ViewState["Value"] = txtName.Text.Trim();
            ViewState["Name"] = ddlColumnName.SelectedValue;
        }
        else
        {
            ViewState["Value"] = null;
            ViewState["Name"] = null;
        }

        if (ddlType.SelectedValue != "0")
        {
            ViewState["Type"] = ddlType.SelectedValue;
        }
        else
        {
            ViewState["Type"] = null;
        }
        dataBindClient();
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvClientList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvClientList.PageCount)
            {
                this.gvClientList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvClientList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindClient();
    }

 
    protected void btnClose_Click(object sender, EventArgs e)
    {
        CloseSelectRoles();
    }

    protected void btnSub_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            lblError.Visible = false;
            hidClientID.Value = Request["chkSelected"];
            int id = 0;
            int.TryParse(Request["chkSelected"], out id);
            txtClientName.Text = GetClientName(id);           
            CloseSelectRoles();
         
        }
        else
        {
            lblError.Visible = true;           
        }
    }

    private string GetClientName(int id)
    {
        string name = string.Empty;
        Sy_ClientQuery query = clientManage.GetClient(id);
        if (query != null)
        {
            name = query.CNName;
        }
        return name;
    }

    /// <summary>
    ///
    /// </summary>
    private void CloseSelectRoles()
    {
        myDiv.Style.Add("display", "none");
        divError.Style.Add("display", "none");       
    }


    protected void lbtnClientSel_Click(object sender, EventArgs e)
    {
        myDiv.Style.Add("display", "block");
        divError.Style.Add("display", "block");
    }
    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {

        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("LoginID", txtLoginID.Text.Trim());
        DataTable dt = userManage.GetUsersList(" select * from Users where LoginID=@LoginID", parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            Jscript.Alert(Resources.Messages.UserIsExit, this.Page);
            return;
        }
        else
        {
            UsersQuery usersQuery = new UsersQuery();
            usersQuery.LoginID = txtLoginID.Text.Trim();
            usersQuery.Password = StringUtil.EncryptPassword(txtPassword.Text.Trim(), "MD5");
            usersQuery.UserName = txtUserName.Text.Trim();
            usersQuery.Email = txtEmail.Text.Trim();
            if (radYes.Checked)
            {
                usersQuery.IsActivity = 1;
            }
            else
            {
                usersQuery.IsActivity = 0;
            }

            StringBuilder sb = new StringBuilder();
            foreach (ListItem item in chkRolesList.Items)
            {
                if (item.Selected)
                {
                    sb.Append(item.Value + ",");
                }
            }
            string roles = sb.ToString();
            if (roles.Length > 0)
            {
                roles = roles.Substring(0, roles.Length - 1);
            }
            usersQuery.Roles = roles;
            if (hidClientID.Value != string.Empty)
            {
                int id=0;
                int.TryParse(hidClientID.Value,out id);
                usersQuery.ClientID = id;
            }
            else
            {
                usersQuery.ClientID = 0;

            }
            try
            {
                if (userManage.UserInsert(usersQuery))
                {                  
                    Jscript.AlertAndRedirect(Resources.Messages.AddSuccess, "UsersList.aspx", this.Page);
                }
                else
                {
                    Jscript.Alert(Resources.Messages.AddFailed, this.Page);
                }
            }
            catch
            {
                Jscript.Alert(Resources.Messages.AddFailed, this.Page);
            }
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("UsersList.aspx");
    }
    
}
